﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace HitchHikersGuideToTheGalaxy.Models
{
    /// <summary>
    /// Vehicle repository class
    /// </summary>
    public class VehicleRepository : HitchHikersGuideToTheGalaxy.Models.IVehicleRepository
    {
        GalaxyDataContext db = new GalaxyDataContext();

        #region Default Add, Delete and save actions

        /// <summary>
        /// Add vehicle
        /// </summary>
        /// <param name="vehicle"></param>
        public void Add(Vehicle vehicle)
        {
            db.Vehicles.InsertOnSubmit(vehicle);
        }

        /// <summary>
        /// Delete vehicle
        /// </summary>
        /// <param name="vehicle"></param>
        public void Delete(Vehicle vehicle)
        {
            db.Vehicles.DeleteOnSubmit(vehicle);
        }

        /// <summary>
        /// Save changes to database
        /// </summary>
        public void Save()
        {
            db.SubmitChanges();
        }

        #endregion

        #region Querys

        /// <summary>
        /// Find all vehicles
        /// </summary>
        /// <returns></returns>
        public IQueryable<Vehicle> FindAllVehicles()
        {
            return db.Vehicles;
            //TODO: Fá fuel og sort með???
        }

        /// <summary>
        /// Find all my vehicles
        /// </summary>
        /// <param name="ssn"></param>
        /// <returns></returns>
        public IQueryable<Vehicle> FindMyVehicles(String ssn)
        {
            return from v in db.Vehicles
                   from vd in db.VehicleDrivers
                   where v.Id == vd.VehicleId && vd.UserInfoSSN == ssn
                   select v;
            //TODO: Fá fuel og sort með???
        }

        /// <summary>
        /// Get one Vehicle from numberPlate
        /// </summary>
        /// <param name="numberPlate"></param>
        /// <returns></returns>
        public Vehicle FindVehicle(string numberPlate)
        {
            //return (from v in db.Vehicles
            //       where v.NumberPlate == numberPlate
            //       select v).Sin;
            return db.Vehicles.SingleOrDefault(d => d.NumberPlate == numberPlate);
        }

        /// <summary>
        /// Check if Vehicle is already registered.
        /// </summary>
        /// <param name="numberPlate"></param>
        /// <returns></returns>
        public bool IsVehicleRegistered(string numberPlate)
        {
            int count = (from v in db.Vehicles
                         where v.NumberPlate == numberPlate
                         select v).Count();

            if (count == 0)
            {
                return false;
            }
            else
            {
                return true;
            }
        }

        #endregion
    }
}
